﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Configuration;
using ScoutOffice.BLL;
using System.Data;

namespace ScoutOffice.DAL
{
    public class ScoutManager
    {
        private static SqlConnection connection;

        public static void InsertScout(Guid scoutId, string firstName, string lastName)
        {
            int rowsAffected;
            using (SqlConnection connection = GetConnection())
            {
                using (SqlCommand command = connection.CreateCommand())
                {
                    command.CommandText = "INSERT INTO SCOUT VALUES (@ScoutId, @FirstName, @LastName)";
                    command.Parameters.AddWithValue("ScoutId", scoutId);
                    command.Parameters.AddWithValue("FirstName", firstName);
                    command.Parameters.AddWithValue("LastName", lastName);
                    rowsAffected = command.ExecuteNonQuery();
                }
            }
        }

        public static Scout FetchScoutByScoutId(Guid scoutId)
        {
            Scout s = null;
            using (SqlConnection connection = GetConnection())
            {
                using (SqlCommand command = connection.CreateCommand())
                {
                    command.CommandText = "SELECT FirstName, LastName FROM SCOUT WHERE SCOUTID = @ScoutId";
                    command.Parameters.AddWithValue("ScoutId", scoutId);
                    using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow))
                    {
                        if (reader.Read())
                        {
                            string firstName = (string)reader["FirstName"];
                            string lastName = (string)reader["LastName"];
                            s = new Scout(scoutId, firstName, lastName);
                        }
                    }
                }
            }
            return s;
        }
        
        private static SqlConnection GetConnection()
        {
            if (connection == null)
            {
                connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ScoutOffice.DAL.Properties.Settings.SqlExpressConnectionString"].ConnectionString);
            }
            connection.Open();
            return connection;
        }
    }
}
